package com.hh.client.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class DiscoveryController {

    @Autowired
    private DiscoveryClient discoveryClient;

    /**
     * 通过应用名称找到服务的ip 端口 在Java代码中发起HTTP请求
     * socket tcp
     * @param serviceName
     * @return
     */
    @GetMapping("/test")
    public String doDiscover(String serviceName) {
        // 服务发现 通过服务名称找到服务的具体实例的过程
        // 服务发现
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
        instances.forEach(System.out::println);
        ServiceInstance serviceInstance = instances.get(0);
        String ip = serviceInstance.getHost();
        int port = serviceInstance.getPort();
        System.out.println("ip = " + ip);
        System.out.println("port = " + port);
        return instances.get(0).toString();
    }
}
